#include "exportgoods.h"
#include "ui_exportgoods.h"

Exportgoods::Exportgoods(QWidget *parent,int sid) :
    QDialog(parent),
    ui(new Ui::Exportgoods)
{
    ui->setupUi(this);
    m_sid = sid;
    myDatabase.getConnection();
}

Exportgoods::~Exportgoods()
{
    delete ui;
}

void Exportgoods::on_Ensure_clicked()
{
    QString gname = ui->gname->text();

    QSqlQuery sql;
    sql.prepare("SELECT* FROM tb_goodsinstore WHERE sid = :sid AND name = :name");
    sql.bindValue(":sid",m_sid);
    sql.bindValue(":name",gname);
    qDebug()<<m_sid<<gname;
    sql.exec();
    if(!sql.first()){
        QMessageBox::information(this,"提示","没有此货物!",QMessageBox::Ok);
        this->~Exportgoods();
    }
    else{
        int gid = sql.value("gid").toInt();
        int num = sql.value("num").toInt();
        sql.prepare("DELETE FROM tb_goodsinstore WHERE sid = :sid AND name = :name");
        sql.bindValue(":sid",m_sid);
        sql.bindValue(":name",gname);
        qDebug()<<"gid, num =  "<<gid<<" "<<num;
        sql.exec();

        sql.prepare("SELECT* FROM tb_goods WHERE gid = :gid");
        sql.bindValue(":gid",gid);
        qDebug()<<"2";
        sql.exec();
        sql.first();
        QVariant currentCat = sql.value("gcat");
        int currentNum = sql.value("gnum").toInt();

        sql.prepare("UPDATE tb_goods SET gnum = :newNUM WHERE gid = :gid");
        sql.bindValue(":newNum",currentNum - num);
        sql.bindValue(":gid",gid);
        qDebug()<<"3";
        sql.exec();

        sql.prepare("SELECT* FROM tb_goods_cat WHERE cname = :currentCat");
        sql.bindValue(":currentCat",currentCat);
        sql.bindValue(":gid",gid);
        qDebug()<<"4";
        sql.exec();
        sql.first();
        int currentNum2 = sql.value("cnum").toInt();

        sql.prepare("UPDATE tb_goods_cat SET cnum = :newNUM WHERE cname = :currentCat");
        sql.bindValue(":newNum",currentNum2 - num);
        sql.bindValue(":currentCat",currentCat);
        qDebug()<<"5";
        sql.exec();
        QMessageBox::information(this,"提示","更新成功!",QMessageBox::Ok);
    }
    this->~Exportgoods();
}

